package dai.samples.mybatis.interceptor;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import dai.samples.mybatis.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 *
 * @author daify
 * @date 2019-08-01
 **/
@Component
@Intercepts({
        // 拦截Executor的query的操作
        @Signature(
                type = Executor.class,
                method = "update",
                // 拦截方法的参数
                args = { MappedStatement.class, 
                         Object.class
                }
        )
})
@Slf4j
public class ExecutorUpdatePlugin implements Interceptor {
    
    @Override 
    public Object intercept(Invocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        log.info("ExecutorUpdatePlugin拦截内容，拦截类:{},拦截方法:{}",
                method.getDeclaringClass().getName(),method.getName());
        Object[] args = invocation.getArgs();
        // 获取mapped执行操作
        MappedStatement ms = (MappedStatement)args[0];
        log.info("ExecutorUpdatePlugin拦截内容，mapper地址:{}",ms.getResource());
        log.info("ExecutorUpdatePlugin拦截内容，mapper方法:{}",ms.getId());
        doSame(args[1]);
        // 主要的业务
        return invocation.proceed();
    }

    /**
     * 实现自己的业务
     * @param o
     */
    public void doSame(Object o) {
        if (o != null && o instanceof User) {
            if (((User) o).getId() == null) {
                long id = IdWorker.getId();
                ((User) o).setId(id);
                log.info("设置默认的ID：{}",id);
            }
        }
    }

    /**
     * 将这个类作为包装类假如拦截链
     * @param o
     * @return
     */
    @Override 
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    /**
     * 设置参数
     * @param properties
     * @return
     */
    @Override 
    public void setProperties(Properties properties) {

    }
}
